/**
 * Copyright (c) 2025   All rights reserved.
 * <p>
 * https://www.sdl.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.sdl.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import io.sdl.common.service.impl.BaseServiceImpl;
import io.sdl.dao.TokenDao;
import io.sdl.entity.TokenEntity;
import io.sdl.service.TokenService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.Optional;
import java.util.UUID;


@Service
public class TokenServiceImpl extends BaseServiceImpl<TokenDao, TokenEntity> implements TokenService {

	@Resource
	private TokenDao tokenDao;

	/**
	 * 12小时后过期
	 */
	private final static int EXPIRE = 3600 * 12;

	@Override
	public TokenEntity getByTokenAMobile(String token, String mobile) {
		return baseDao.getByTokenAMobile(token, mobile);
	}

	@Override
	public TokenEntity getByToken(String token) {
		return baseDao.getByToken(token);
	}


	@Override
	public TokenEntity createToken(Long userId) {
		//当前时间
		Date now = new Date();
		//过期时间
		Date expireTime = new Date(now.getTime() + EXPIRE * 14);

		//用户token
		String token;

		//判断是否生成过token
		TokenEntity tokenEntity = baseDao.getByUserId(userId);
		if (tokenEntity == null) {
			//生成一个token
			token = generateToken();

			tokenEntity = new TokenEntity();
			tokenEntity.setUserId(userId);
			tokenEntity.setToken(token);
			tokenEntity.setUpdateDate(now);
			tokenEntity.setExpireDate(expireTime);

			//保存token
			this.insert(tokenEntity);
		} else {
			//判断token是否过期
			if (tokenEntity.getExpireDate().getTime() < System.currentTimeMillis()) {
				//token过期，重新生成token
				token = generateToken();
			} else {
				token = tokenEntity.getToken();
			}

			tokenEntity.setToken(token);
			tokenEntity.setUpdateDate(now);
			tokenEntity.setExpireDate(expireTime);

			//更新token
			this.updateById(tokenEntity);
		}

		return tokenEntity;
	}
	/*
	 *token续期
	 * @param userId 用户id
	 * @param login 登录状态
	 */
	@Override
	public void expireToken(Long userId,boolean login) {
		TokenEntity token = tokenDao.getByUserId(userId);
		Calendar instance = Calendar.getInstance();
		//当前时间
		Date now = instance.getTime();


		//向后续期
		if(login){
			instance.add(Calendar.DAY_OF_WEEK, 7);
		}else{
			instance.add(Calendar.DAY_OF_WEEK, -7);
		}

		Date expireTime = instance.getTime();
		token.setExpireDate(expireTime);
		token.setUpdateDate(now);

		tokenDao.updateById(token);
	}

	@Override
	public Optional<String> validateToken(String token) {
		Long userId = baseDao.getByToken(token).getUserId();
		return userId.equals(token) ? Optional.empty() : Optional.of(String.valueOf(userId));
	}

	@Override
	public TokenEntity checkToken(String token, String time) {

		return baseDao.checkToken(token, time);
	}

	private String generateToken() {
		return UUID.randomUUID().toString().replace("-", "");
	}
}
